from appium import webdriver
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 定义基类
class Base():
    # 第一个方法，初始化方法，生成驱动对象 driver
    def __init__(self):
        # 启动项参数
        cap={
            "platformName": "Android",
            "appium:deviceName": "emulator-5554",
            "appium:appPackage": "com.kongfz.app",
            "appium:appActivity": "com.kongfz.app.home.mvvm.homepage.HomeActivity",
            "noReset": True
        }
        # 生成驱动对象 driver
        self.driver=webdriver.Remote('http://127.0.0.1:4723/wd/hub',cap)
        self.driver.implicitly_wait(25)
        sleep(20)

    # 封装一个定位元素的方法 普通定位元素的方法 loc=(By.ID,"SSSS") (By.XPATH,"SSSS")
    def loc_ele(self,loc):
        try:
            return self.driver.find_element(*loc)
        except:
            print("未定位到元素的变量值：",loc)

    # 显示等待 定位元素方法
    def loc_wait_ele(self,loc):
        try:
            return WebDriverWait(self.driver, 15, 0.5).until(EC.presence_of_element_located(loc))
        except:
            print("未定位到元素的变量值：", loc)

    # uiautomator定位元素的方法 loc='new UiSelector().text("")'  /  'new UiSelector().resourceId("")'
    def loc_ui_ele(self,loc):
        try:
            return self.driver.find_element_by_android_uiautomator(loc)
        except:
            print("未定位到元素的变量值：", loc)

    # 截屏
    def jieping(self,filenme):
        # 获取当前时间
        t=time.strftime('%Y%m%d%H%M%S',time.localtime())
        # 截屏
        self.driver.save_screenshot(t + filenme)


    def get_key_value(self,loc,key):
        if type(loc)==str:
            ele=self.loc_ui_ele(loc)
        else:
            ele=self.loc_ele(loc)
        return ele.get_attribute(key)

    # 退出应用的方法
    def quit_driver(self):
        self.driver.quit()






